package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 兴趣使然黄小黄
 * @version 1.0
 * @date 2023/3/14 15:57
 */
@WebServlet("/authorInfo")
@SuppressWarnings({"all"})
public class AuthorServlet extends HttpServlet {

    ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset=utf8");
        // 该方法用于处理博客详情页的用户信息
        String param = req.getParameter("blogId"); // 先获取文章的的 blogId
        if (param == null || "".equals(param)) {
            // 缺少参数
            resp.getWriter().write("{\"ok\": false, \"reason\": \"参数缺失\"}");
            return;
        }
        // 先在数据库中查找对应的 blog 对象, 在根据对应的 blog对象 的 userId 查找 user
        BlogDao blogDao = new BlogDao();
        Blog blog = blogDao.selectOne(Integer.parseInt(param));
        if (blog == null) {
            // 不存在对应的博文
            resp.getWriter().write("{\"ok\": false, \"reason\": \"要查询的博客不存在\"}");
            return;
        }
        UserDao userDao = new UserDao();
        User author = userDao.selectById(blog.getUserId());
        if (author == null) {
            // 不存在对应的作者
            resp.getWriter().write("{\"ok\": false, \"reason\": \"要查询的作者不存在\"}");
            return;
        }
        // 将用户对象以 json 的形式返回响应
        // 避免将密码传到前端
        author.setPassword("");
        resp.getWriter().write(objectMapper.writeValueAsString(author));
    }
}
